import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import { getItem, setItem, removeItem } from '@/utils/cookieUtil'
import { reqUserMeInfo, reqUserMenuList } from '@/api/user'
import { Message } from 'element-ui'

Vue.use(VueRouter)

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
	return originalPush.call(this, location).catch(err => err)
}


/**
 * 静态路由
 */
export const constantRouterMap = [

	// 重定向，每次访问*都定向到首页
	// {
	// 	path: '',
	// 	redirect: '/index',
	// 	hidden: true,
	// },
	{
		path: '/',
		meta: {
			icon: null,
			title: null,
		},
		hidden: true,
		sort: null,
		component: () => import('@/views/home'),
	},
	{
		path: '/login',
		meta: {
			icon: null,
			title: null,
		},
		hidden: true,
		sort: null,
		component: () => import('@/views/login'),
	},
	{
		path: '/course-center',
		meta: {
			icon: null,
			title: null,
		},
		hidden: true,
		sort: null,
		component: () => import('@/views/course-center'),
	},
	{
		path: '/course/:id',
		meta: {
			icon: null,
			title: null,
		},
		hidden: true,
		sort: null,
		component: () => import('@/views/course'),
	},
	
	{
		path: '/404',
		meta: {
			icon: null,
			title: null,
		},
		hidden: true,
		sort: null,
		component: () => import('@/views/error')
	},
	{
		path: '*',
		redirect: '/404',
		hidden: true
	},

]
/**
 * 动态路由
 */
export const asyncRouterMap = [


]


const router = new VueRouter({
	mode: "history",
	routes: constantRouterMap,
	// // 控制路由跳转滚动条的位置为最顶部
	scrollBehavior(to, from, savedPosition) {
		// 始终滚动到顶部，y代表距离顶部的距离
		return { y: 0 }
	},
})

// const whiteList = ['/login', '/file/share/'] // 不重定向白名单

router.beforeEach((to, from, next) => {
	// if (getItem("token")) {
	// 	if (to.path === '/login') {
	// 		next({ path: '/' })
	// 	} else {
	// 		if (store.state.user.roleList.length == 0) {
	// 			// 拉取用户信息
	// 			getUserInfo(next);
	// 		}
	// 		if (to.path.match('/backend/admin') && store.state.user.roleList.length === 1) {
	// 			next({ path: '/' })
	// 		}
	// 		next()
	// 	}
	// } else {
	// 	next();
	// 	// if (to.path == '/login') {
	// 	// 	next()
	// 	// } else {
	// 	// 	next("/login")
	// 	// }
	// }
	next()
})

router.afterEach(() => {

});

function getUserInfo(next) {
	reqUserMeInfo().then(res => {
		store.dispatch('setUserInfo', res.data);
		if (res.data.roleList.length > 1) {
			getUserMenuList(next);
		}
	}).catch(error => {
		if (error.code == 401) {
			removeItem("token");
			Message.error({
				message: "身份过期，请重新登录"
			});
		} else {
			Message.error({
				message: error.msg
			});
		}
	})
}

function getUserMenuList(next) {
	reqUserMenuList().then(res => {
		// 生成可访问的路由表
		store.dispatch('GenerateRoutes', {
			menus: res.data
		}).then(() => {
			// 动态添加可访问路由表
			router.addRoutes(store.state.menu.addRouters);
			next()
		})
	}).catch(error => {
		console.log(error);

	})
}



export default router